<template>
  <div id="permission-list">
    <h1>权限管理</h1>
    <el-table :data="permissions" style="width: 100%">
      <el-table-column prop="id" label="权限ID"></el-table-column>
      <el-table-column prop="username" label="权限名称"></el-table-column>
      <el-table-column prop="permission" label="权限等级">
        <template slot-scope="scope">
          <el-select v-model="scope.row.permission" placeholder="请选择权限等级">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="普通管理员" value="普通管理员"></el-option>
            <el-option label="注册用户" value="注册用户"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="savePermission(scope.$index)">保存</el-button>
          <el-button size="mini" type="danger" @click="deletePermission(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { fetchPermissions, updatePermission, deletePermission } from '../api/api.js';
export default {
  name: 'permissionlist',
  data() {
    return {
      permissions: []
    };
  },
  created() {
    this.fetchPermissions();
  },
  methods: {
    fetchPermissions() {
      fetchPermissions()
        .then(response => {
          this.permissions = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    savePermission(index) {
      const permission = this.permissions[index];
      const updatepermission = permission.permission;
      updatePermission(permission.id, updatepermission)
        .then(response => {
          this.$message.success('保存成功');
        })
        .catch(error => {
          console.error(error); 
          this.$message.error('保存失败');
        });
    },
    deletePermission(index) {
      const permission = this.permissions[index];
      deletePermission(permission.id)
        .then(response => {
          this.permissions.splice(index, 1);
          this.$message.success('删除成功');
        })
        .catch(error => {
          console.log(error);
          this.$message.error('删除失败');
        });
    },
  }
};
</script>

<style scoped>
#permission-list {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
  border-radius: 5px;
}

h1 {
  text-align: center;
  color: #333;
}

el-table {
  width: 100%;
  margin-top: 20px;
  border-collapse: collapse;
}

el-table-column {
  padding: 10px;
  border: 1px solid #ccc;
}

el-select,
el-button {
  width: 100%;
}

el-button {
  margin-left: 10px;
}

el-button.mini {
  padding: 5px 10px;
  font-size: 14px;
}

el-button.mini.primary {
  background-color: #409eff;
  color: #fff;
}

el-button.mini.danger {
  background-color: #f56c6c;
  color: #fff;
}
</style>
